package com.scs.application.modules.wm.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.annotation.MatrCanPass;
import com.scs.application.modules.base.dto.ExpandColumnDTO;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.dto.StockByPackTempDTO;
import com.scs.application.modules.wm.entity.WorkOrder;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.enums.WorkOrderType;
import com.scs.application.modules.wm.mapper.InOrderMapper;
import com.scs.application.modules.wm.service.InOrderItemService;
import com.scs.application.utils.ImportResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 入库单明细 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/wm/in_order_item")
public class InOrderItemController extends CrudController<InOrderItemService, WorkOrderItem> {

    @Resource
    private InOrderMapper inOrderMapper;

    @GetMapping("/get_barcode")
    public RestResult getLineId(@RequestParam("workOrderItemId") String workOrderItemId,
                                @RequestParam("workOrderId") String workOrderId) {
        List<WorkOrderItem> barorders=service.getLineId(workOrderItemId,workOrderId);
        String lineId=barorders.get(0).getLineId();
        return  RestResult.ok("success",lineId);
    }

    /**
     * 跟台包入库
     * @param stockByPackTempDTO
     * @return
     */
    @PostMapping("addByPackTemp")
    public RestResult addByTemp(@RequestBody StockByPackTempDTO stockByPackTempDTO) {
        return RestResult.ok("添加成功", service.addByPackTemp(stockByPackTempDTO));
    }

    /**
     * 修改包装数量及单品数量
     * @param workOrderItem
     * @return
     */
    @PostMapping("/updateQty")
    public RestResult updateQty(@RequestBody WorkOrderItem workOrderItem){
        service.updateQty(workOrderItem);
        return  RestResult.ok("success");
    }

    /**
     * 删除跟台包
     * @param id
     * @return
     */
    @DeleteMapping("/deletePackage")
    public RestResult deletePackage(@RequestParam("id") String id ) {
        service.deletePackage(id);
        return  RestResult.ok("success");
    }

    /**
     * 删除跟台包内耗材
     * @param id
     * @return
     */
    @DeleteMapping("/deleteMatr")
    public RestResult deleteMatr(@RequestParam("id") String id ) {
        service.deleteMatr(id);
        return  RestResult.ok("success");
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    @MatrCanPass(businessType = "warehousing_item")//手动入库耗材禁用校验
    public RestResult saveItem(@Valid @RequestBody WorkOrderItem entity) {
        if(entity.getExpDate()==null) throw new BusinessException("效期不能为空");
        if(DateUtils.getDateDiffOfDays(new Date(),entity.getExpDate()) <0) throw new BusinessException("效期不能早于当前日期");

        boolean isOk = service.saveOrUpdate(entity);
        this.fillDataOne(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功",  entity);
    }

    @Override
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Page<WorkOrderItem> page = service.inorderItemPage(queryContext);
        this.fillDataPage(page);
        return PageResult.ok("查询成功", page.getRecords() , page.getTotal());
    }

    private void fillDataPage (Page<WorkOrderItem> page ) {
        if (page.getRecords() == null || page.getRecords().size() == 0) {
            return;
        }
        WorkOrder workOrder = inOrderMapper.selectById(page.getRecords().get(0).getWorkOrderId());
        if (workOrder ==null || !WorkOrderType.IN_PACKAGE.equals(workOrder.getBusType())) {
            return;
        }
        List<WorkOrderItem> workOrderItemList = page.getRecords();

        // 包
        List<WorkOrderItem> workOrderItemPackList = workOrderItemList.stream().filter(item -> "1".equals(item.getMatrType())).collect(Collectors.toList());

        // 包明细
        Map<String,List<WorkOrderItem>> workOrderItemChildList = workOrderItemList.stream()
                .filter(item -> !"1".equals(item.getMatrType()) && StringUtils.isNotBlank(item.getPackItemId()))
                .collect(Collectors.groupingBy(WorkOrderItem::getPackItemId));
        if (workOrderItemChildList == null || workOrderItemChildList.size() == 0) {
            return;
        }

        List<ExpandColumnDTO> childCols;
        ExpandColumnDTO expandColumnDTO;

        for(WorkOrderItem packItem : workOrderItemPackList){
            packItem.setShowExpand(true);
            packItem.setChildData(workOrderItemChildList.get(packItem.getId()));

            childCols = new ArrayList<>();
            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("matrName").setTitle("商品名称").setColumnWidth(220);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("matrSpec").setTitle("商品规格").setColumnWidth(100);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("packageUnit").setTitle("包装单位").setColumnWidth(80);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("packageQty").setTitle("包装数量").setColumnWidth(80);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("amount").setTitle("金额").setColumnWidth(80);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("lot").setTitle("批号").setColumnWidth(80);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("expDate").setTitle("效期").setColumnWidth(120).setDatePattern(DateUtils.DATE_PATTERN);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("mfgDate").setTitle("生产日期").setColumnWidth(120).setDatePattern(DateUtils.DATE_PATTERN);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("sterilizationDate").setTitle("灭菌日期").setColumnWidth(120).setDatePattern(DateUtils.DATE_PATTERN);
            childCols.add(expandColumnDTO);

            expandColumnDTO = new ExpandColumnDTO();
            expandColumnDTO.setField("sterilizationIndate").setTitle("灭菌效期").setColumnWidth(120).setDatePattern(DateUtils.DATE_PATTERN);
            childCols.add(expandColumnDTO);
            packItem.setChildCols(childCols);
        }
        page.setRecords(workOrderItemPackList);
        page.setTotal(workOrderItemPackList.size());
    }

    private void fillDataOne (WorkOrderItem workOrderItemPack ) {
        WorkOrder workOrder = inOrderMapper.selectById(workOrderItemPack.getWorkOrderId());
        if (workOrder ==null || !WorkOrderType.IN_PACKAGE.equals(workOrder.getBusType())) {
            return;
        }
        workOrderItemPack.setChildData(service.list(Wrappers.<WorkOrderItem>query().eq("pack_item_id",workOrderItemPack.getId()).isNotNull("pack_item_id")));
    }

    /**
     * 修改包装数量及单品数量
     * @param workOrderItem
     * @return
     */
    @PostMapping("/splitOrderItem")
    public RestResult splitOrderItem(@RequestBody WorkOrderItem workOrderItem){
        service.splitOrderItem(workOrderItem);
        return  RestResult.ok("success");
    }

    /**
     * @description: 下载导入模板
     **/
    @GetMapping("/downloadExcelTemp/{deliveryId}")
    public void downloadExcelTemp(HttpServletResponse response, @PathVariable(name = "deliveryId") String deliveryId) {
        service.downloadExcelTemp(response,deliveryId);
    }

    /**
     * 导入数据到后端
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/importDtl")
    public RestResult<ImportResult> importDtl(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request)  {
        return RestResult.ok("导入成功", service.importDtl(file, request.getParameter("deliveryId")));
    }



}
